import 'package:cached_network_image/cached_network_image.dart';
import 'package:cher_flare/config/url_api.dart';
import 'package:cher_flare/http/http_utils.dart';
import 'package:cher_flare/utils/app_color.dart';
import 'package:cher_flare/utils/ly_data_manager.dart';
import 'package:cher_flare/utils/size_fit.dart';
import 'package:cher_flare/utils/utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../models/ly_friend_model.dart';

class LYFollowListPage extends StatefulWidget {
  const LYFollowListPage({super.key});

  @override
  State<LYFollowListPage> createState() => _LYFollowListPageState();
}

class _LYFollowListPageState extends State<LYFollowListPage> {
  final refreshController = EasyRefreshController(controlFinishLoad: true);
  int page = 1;
  List<LyFriendModel> dataList = [];

  @override
  void initState() {
    super.initState();
    _requestFollowList();
  }

  void _unfollowButtonDidClick(LyFriendModel model) async {
    EasyLoading.show();
    final response = await HttpUtils.getInstance
        .post(URLApi.unfriend, data: {'followUserId': model.userId});
    final userModel = await LYDataManager.share.searchUser(model.userId ?? '');
    userModel?.isFriend = false;
    LYDataManager.share.updateUserInfo();
    page = 1;
    dataList.clear();
    _requestFollowList();
    EasyLoading.dismiss();
  }

  void _requestFollowList() async {
    EasyLoading.show();
    final response = await HttpUtils.getInstance
        .post(URLApi.getFriendsListPage, data: {'limit': 20, 'page': page});
    if (response.isSuccess && response.data is List) {
      for (final json in response.data) {
        final model = LyFriendModel.fromJson(json);
        dataList.add(model);
      }
    }
    refreshController.finishLoad();
    setState(() {});
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Utils.commonAppBar(title: 'Follow List'),
      backgroundColor: AppColors.whiteColor,
      body: dataList.isNotEmpty
          ? EasyRefresh.builder(
              controller: refreshController,
              onLoad: () {
                page += 1;
                _requestFollowList();
              },
              childBuilder: (ctx, phy) {
                return ListView.builder(
                  padding: const EdgeInsets.only(top: 12),
                  itemBuilder: (ctx, index) {
                    final model = dataList[index];
                    return _makeItemWidget(model);
                  },
                  itemCount: dataList.length,
                  itemExtent: 76.px,
                );
              })
          : _makeEmpty(),
    );
  }

  Widget _makeEmpty() {
    return Container(
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/start_your_creation_img.png',
            width: 189,
            height: 143,
          ),
          SizedBox(
            height: 20.px,
          ),
          Text(
            'no data',
            style: TextStyle(
                color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.5), fontSize: 16),
          )
        ],
      ),
    );
  }

  Widget _makeItemWidget(LyFriendModel model) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(22),
                  child: CachedNetworkImage(
                    imageUrl: model.avatarUrl ?? '',
                    width: 44,
                    height: 44,
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        model.nickname ?? '',
                        style: const TextStyle(
                            color: AppColors.color404040, fontSize: 14),
                      ),
                      const SizedBox(
                        height: 8,
                      ),
                      Text(
                        '${model.age ?? 0} ${model.country ?? ''}',
                        style: TextStyle(
                            color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.6),
                            fontSize: 12),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () => _unfollowButtonDidClick(model),
            child: Container(
              height: 30.px,
              width: 71.px,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: AppColors.color454545,
                  borderRadius: BorderRadius.circular(15.px)),
              child: const Text(
                'Unfollow',
                style: TextStyle(color: AppColors.whiteColor, fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
